#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
DeepSeek AI集成模块 - 智能生成项目描述
"""

import requests
import os
import json
from typing import Dict, List, Optional, Tuple
from utils.logger import get_logger


class DeepSeekAI:
    """DeepSeek AI客户端"""
    
    def __init__(self, api_key: str = ""):
        self.api_key = api_key
        self.base_url = "https://api.deepseek.com/v1"  # 假设的API端点
        self.logger = get_logger("DeepSeekAI")
        
        # 如果没有API Key，使用本地智能分析
        self.use_local_analysis = not bool(api_key.strip())
        
        if self.use_local_analysis:
            self.logger.info("DeepSeek API Key未配置，将使用本地智能分析")
        else:
            self.logger.info("DeepSeek AI客户端初始化完成")
    
    def analyze_project_files(self, project_path: str) -> Dict[str, str]:
        """分析项目文件，提取关键信息"""
        analysis = {
            'language': 'Unknown',
            'framework': 'Unknown',
            'description': '',
            'keywords': []
        }
        
        try:
            # 收集项目信息
            file_types = {}
            key_files = []
            total_files = 0
            
            for root, dirs, files in os.walk(project_path):
                # 跳过隐藏目录和常见的忽略目录
                dirs[:] = [d for d in dirs if not d.startswith('.') and d not in ['__pycache__', 'node_modules', 'venv', 'env']]
                
                for file in files:
                    if file.startswith('.'):
                        continue
                    
                    total_files += 1
                    file_ext = os.path.splitext(file)[1].lower()
                    file_types[file_ext] = file_types.get(file_ext, 0) + 1
                    
                    # 收集关键文件
                    if file.lower() in ['readme.md', 'main.py', 'index.js', 'app.py', 'package.json', 'requirements.txt']:
                        file_path = os.path.join(root, file)
                        try:
                            with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
                                content = f.read()[:1000]  # 只读前1000个字符
                                key_files.append({
                                    'name': file,
                                    'content': content
                                })
                        except:
                            pass
            
            # 分析主要语言
            if '.py' in file_types:
                analysis['language'] = 'Python'
                analysis['keywords'].extend(['python', '数据分析', '机器学习'])
            elif '.js' in file_types:
                analysis['language'] = 'JavaScript'
                analysis['keywords'].extend(['javascript', 'web开发', '前端'])
            elif '.java' in file_types:
                analysis['language'] = 'Java'
                analysis['keywords'].extend(['java', '后端开发'])
            elif '.cpp' in file_types or '.c' in file_types:
                analysis['language'] = 'C/C++'
                analysis['keywords'].extend(['c++', '系统编程'])
            
            # 分析框架和类型
            for file_info in key_files:
                content = file_info['content'].lower()
                if 'flask' in content:
                    analysis['framework'] = 'Flask'
                    analysis['keywords'].append('web框架')
                elif 'django' in content:
                    analysis['framework'] = 'Django'
                    analysis['keywords'].append('web框架')
                elif 'tkinter' in content:
                    analysis['framework'] = 'Tkinter'
                    analysis['keywords'].append('桌面应用')
                elif 'opencv' in content:
                    analysis['keywords'].extend(['计算机视觉', '图像处理'])
                elif 'pandas' in content or 'numpy' in content:
                    analysis['keywords'].extend(['数据分析', '数据科学'])
                elif 'tensorflow' in content or 'torch' in content:
                    analysis['keywords'].extend(['机器学习', '深度学习'])
            
            return analysis
            
        except Exception as e:
            self.logger.error(f"分析项目文件失败: {e}")
            return analysis
    
    def generate_description(self, project_name: str, project_path: str) -> str:
        """生成项目描述"""
        try:
            # 分析项目文件
            analysis = self.analyze_project_files(project_path)
            
            if self.use_local_analysis:
                return self._generate_local_description(project_name, analysis)
            else:
                return self._generate_ai_description(project_name, analysis, project_path)
                
        except Exception as e:
            self.logger.error(f"生成项目描述失败: {e}")
            return f"基于{analysis.get('language', 'Unknown')}开发的项目"
    
    def _generate_local_description(self, project_name: str, analysis: Dict) -> str:
        """本地智能生成描述"""
        language = analysis.get('language', 'Unknown')
        framework = analysis.get('framework', '')
        keywords = analysis.get('keywords', [])
        
        # 基于项目名称推断类型
        name_lower = project_name.lower()
        project_type = ""
        
        if any(word in name_lower for word in ['管理', 'system', '系统']):
            project_type = "管理系统"
        elif any(word in name_lower for word in ['游戏', 'game']):
            project_type = "游戏"
        elif any(word in name_lower for word in ['爬虫', 'crawler', 'spider']):
            project_type = "数据爬虫"
        elif any(word in name_lower for word in ['分析', 'analysis']):
            project_type = "数据分析"
        elif any(word in name_lower for word in ['识别', 'recognition']):
            project_type = "识别系统"
        elif any(word in name_lower for word in ['计算器', 'calculator']):
            project_type = "计算工具"
        elif any(word in name_lower for word in ['通讯录', 'contact']):
            project_type = "联系人管理"
        else:
            project_type = "应用程序"
        
        # 构建描述
        description_parts = []
        
        if language != 'Unknown':
            description_parts.append(f"基于{language}")
            
        if framework and framework != 'Unknown':
            description_parts.append(f"使用{framework}框架")
        
        description_parts.append(f"开发的{project_type}")
        
        if keywords:
            description_parts.append(f"涉及{', '.join(keywords[:3])}")
        
        description = "，".join(description_parts) + "。"
        
        # 添加功能特点
        if '管理' in name_lower:
            description += "提供数据的增删改查功能。"
        elif '识别' in name_lower:
            description += "具有智能识别和处理能力。"
        elif '分析' in name_lower:
            description += "支持数据可视化和统计分析。"
        
        return description
    
    def _generate_ai_description(self, project_name: str, analysis: Dict, project_path: str) -> str:
        """使用DeepSeek AI生成描述"""
        try:
            # 准备提示词
            prompt = self._build_prompt(project_name, analysis, project_path)
            
            # 调用DeepSeek API
            headers = {
                'Authorization': f'Bearer {self.api_key}',
                'Content-Type': 'application/json'
            }
            
            data = {
                'model': 'deepseek-chat',
                'messages': [
                    {
                        'role': 'system',
                        'content': '你是一个专业的软件项目分析师，擅长为代码项目编写简洁、专业的中文描述。'
                    },
                    {
                        'role': 'user',
                        'content': prompt
                    }
                ],
                'max_tokens': 200,
                'temperature': 0.7
            }
            
            response = requests.post(
                f"{self.base_url}/chat/completions",
                headers=headers,
                json=data,
                timeout=30
            )
            
            if response.status_code == 200:
                result = response.json()
                description = result['choices'][0]['message']['content'].strip()
                self.logger.info("DeepSeek AI生成描述成功")
                return description
            else:
                self.logger.error(f"DeepSeek API调用失败: {response.status_code}")
                return self._generate_local_description(project_name, analysis)
                
        except Exception as e:
            self.logger.error(f"DeepSeek AI调用异常: {e}")
            return self._generate_local_description(project_name, analysis)
    
    def _build_prompt(self, project_name: str, analysis: Dict, project_path: str) -> str:
        """构建AI提示词"""
        prompt = f"""请为以下项目生成一个简洁、专业的中文描述（50字以内）：

项目名称：{project_name}
编程语言：{analysis.get('language', 'Unknown')}
使用框架：{analysis.get('framework', 'Unknown')}
关键词：{', '.join(analysis.get('keywords', []))}

请生成一个适合作为Git仓库描述的简短文本，突出项目的主要功能和技术特点。
"""
        return prompt
    
    def generate_repository_name(self, project_name: str, project_path: str) -> str:
        """生成智能的仓库名称"""
        try:
            # 分析项目文件
            analysis = self.analyze_project_files(project_path)
            
            if self.use_local_analysis:
                return self._generate_local_repo_name(project_name, analysis)
            else:
                return self._generate_ai_repo_name(project_name, analysis, project_path)
                
        except Exception as e:
            self.logger.error(f"生成仓库名称失败: {e}")
            # 回退到基本的名称清理
            from utils.name_translator import name_translator
            return name_translator.clean_name(project_name)
    
    def _generate_local_repo_name(self, project_name: str, analysis: Dict) -> str:
        """本地智能生成仓库名称"""
        language = analysis.get('language', 'Unknown')
        keywords = analysis.get('keywords', [])
        
        # 基于项目名称和分析结果生成更好的名称
        name_lower = project_name.lower()
        
        # 提取关键信息
        name_parts = []
        
        # 添加语言前缀（如果合适）
        if language == 'Python' and 'python' not in name_lower:
            name_parts.append('python')
        elif language == 'JavaScript' and 'js' not in name_lower and 'javascript' not in name_lower:
            name_parts.append('js')
        
        # 分析项目类型并生成核心名称
        core_name = self._extract_core_name(project_name, analysis)
        if core_name:
            name_parts.append(core_name)
        
        # 添加功能后缀
        if any(word in name_lower for word in ['管理', 'management', '系统', 'system']):
            if 'system' not in core_name and 'management' not in core_name:
                name_parts.append('system')
        elif any(word in name_lower for word in ['工具', 'tool', '助手', 'assistant']):
            if 'tool' not in core_name and 'assistant' not in core_name:
                name_parts.append('tool')
        elif any(word in name_lower for word in ['分析', 'analysis']):
            if 'analysis' not in core_name:
                name_parts.append('analyzer')
        
        # 组合名称
        repo_name = '_'.join(name_parts)
        
        # 清理和验证
        repo_name = self._clean_repo_name(repo_name)
        
        return repo_name
    
    def _extract_core_name(self, project_name: str, analysis: Dict) -> str:
        """提取项目的核心名称"""
        # 使用现有的翻译器作为基础
        from utils.name_translator import name_translator
        translated = name_translator.clean_name(project_name)
        
        # 移除常见的通用词汇，保留核心概念
        generic_words = ['project', 'system', 'management', 'tool', 'app', 'application']
        words = translated.split('_')
        
        # 保留有意义的词汇
        meaningful_words = []
        for word in words:
            if word not in generic_words and len(word) > 2:
                meaningful_words.append(word)
        
        # 如果没有有意义的词汇，使用原始翻译
        if not meaningful_words:
            return translated
        
        # 限制长度，保留最重要的词汇
        if len(meaningful_words) > 3:
            meaningful_words = meaningful_words[:3]
        
        return '_'.join(meaningful_words)
    
    def _generate_ai_repo_name(self, project_name: str, analysis: Dict, project_path: str) -> str:
        """使用DeepSeek AI生成仓库名称"""
        try:
            # 准备提示词
            prompt = self._build_name_prompt(project_name, analysis)
            
            # 调用DeepSeek API
            headers = {
                'Authorization': f'Bearer {self.api_key}',
                'Content-Type': 'application/json'
            }
            
            data = {
                'model': 'deepseek-chat',
                'messages': [
                    {
                        'role': 'system',
                        'content': '你是一个专业的软件项目命名专家，擅长为代码项目生成规范的英文仓库名称。仓库名称应该简洁、描述性强、符合GitHub/Gitee命名规范。'
                    },
                    {
                        'role': 'user',
                        'content': prompt
                    }
                ],
                'max_tokens': 50,
                'temperature': 0.3  # 较低的温度以获得更一致的结果
            }
            
            response = requests.post(
                f"{self.base_url}/chat/completions",
                headers=headers,
                json=data,
                timeout=30
            )
            
            if response.status_code == 200:
                result = response.json()
                ai_name = result['choices'][0]['message']['content'].strip()
                
                # 清理AI生成的名称
                cleaned_name = self._clean_repo_name(ai_name)
                self.logger.info(f"DeepSeek AI生成仓库名称成功: {project_name} -> {cleaned_name}")
                return cleaned_name
            else:
                self.logger.error(f"DeepSeek API调用失败: {response.status_code}")
                return self._generate_local_repo_name(project_name, analysis)
                
        except Exception as e:
            self.logger.error(f"DeepSeek AI调用异常: {e}")
            return self._generate_local_repo_name(project_name, analysis)
    
    def _build_name_prompt(self, project_name: str, analysis: Dict) -> str:
        """构建AI名称生成提示词"""
        prompt = f"""请为以下项目生成一个规范的英文仓库名称：

项目名称：{project_name}
编程语言：{analysis.get('language', 'Unknown')}
使用框架：{analysis.get('framework', 'Unknown')}
关键词：{', '.join(analysis.get('keywords', []))}

要求：
1. 只返回仓库名称，不要其他说明
2. 使用小写字母、数字、下划线和中划线
3. 长度不超过30个字符
4. 名称要有描述性，能体现项目功能
5. 符合GitHub/Gitee命名规范

仓库名称："""
        return prompt
    
    def _clean_repo_name(self, name: str) -> str:
        """清理仓库名称"""
        import re
        
        # 移除引号和其他标点
        name = re.sub(r'["\'\`]', '', name)
        
        # 只保留字母、数字、下划线、中划线
        name = re.sub(r'[^a-zA-Z0-9_-]', '_', name)
        
        # 去除连续的下划线和中划线
        name = re.sub(r'[_-]+', '_', name)
        
        # 去除首尾的下划线和中划线
        name = name.strip('_-')
        
        # 转换为小写
        name = name.lower()
        
        # 确保不为空
        if not name:
            return "unnamed_project"
        
        # 限制长度
        if len(name) > 30:
            name = name[:30].rstrip('_-')
        
        # 确保以字母或数字开头
        if name and not (name[0].isalpha() or name[0].isdigit()):
            name = "project_" + name
        
        return name
    
    def batch_generate_names(self, projects: List[Dict]) -> Dict[str, str]:
        """批量生成仓库名称"""
        names = {}
        
        for project in projects:
            project_name = project.get('name', '')
            project_path = project.get('path', '')
            
            if project_name and project_path:
                repo_name = self.generate_repository_name(project_name, project_path)
                names[project_name] = repo_name
                
        return names
    
    def batch_generate_descriptions(self, projects: List[Dict]) -> Dict[str, str]:
        """批量生成项目描述"""
        descriptions = {}
        
        for project in projects:
            project_name = project.get('name', '')
            project_path = project.get('path', '')
            
            if project_name and project_path:
                description = self.generate_description(project_name, project_path)
                descriptions[project_name] = description
                
        return descriptions
    
    def generate_text(self, prompt: str) -> str:
        """
        生成文本内容（通用方法）
        
        Args:
            prompt: 提示词
            
        Returns:
            str: 生成的文本内容
        """
        try:
            if self.use_local_analysis:
                # 本地分析模式，返回简单的提示
                return "本地分析模式：请手动调整README内容"
            
            # 调用DeepSeek API，增加重试机制
            return self._call_deepseek_api_with_retry(prompt)
                
        except Exception as e:
            self.logger.error(f"生成文本时出错: {str(e)}")
            return None
    
    def _call_deepseek_api_with_retry(self, prompt: str, max_retries: int = 3) -> str:
        """带重试机制的DeepSeek API调用"""
        for attempt in range(max_retries):
            try:
                headers = {
                    'Authorization': f'Bearer {self.api_key}',
                    'Content-Type': 'application/json'
                }
                
                data = {
                    'model': 'deepseek-chat',
                    'messages': [
                        {
                            'role': 'system',
                            'content': '你是一个专业的文档编写助手，擅长根据用户需求调整和优化README文档内容。'
                        },
                        {
                            'role': 'user',
                            'content': prompt
                        }
                    ],
                    'max_tokens': 2000,
                    'temperature': 0.7
                }
                
                # 增加超时时间，根据重试次数调整
                timeout = 60 + (attempt * 30)  # 60s, 90s, 120s
                
                self.logger.info(f"尝试调用DeepSeek API (第{attempt + 1}次，超时: {timeout}s)")
                
                response = requests.post(
                    f"{self.base_url}/chat/completions",
                    headers=headers,
                    json=data,
                    timeout=timeout
                )
                
                if response.status_code == 200:
                    result = response.json()
                    if 'choices' in result and len(result['choices']) > 0:
                        content = result['choices'][0]['message']['content']
                        self.logger.info("DeepSeek AI文本生成成功")
                        return content.strip()
                    else:
                        self.logger.warning("DeepSeek API返回格式异常")
                        return None
                else:
                    self.logger.error(f"DeepSeek API调用失败: {response.status_code} - {response.text}")
                    if attempt < max_retries - 1:
                        self.logger.info(f"将在3秒后重试...")
                        import time
                        time.sleep(3)
                        continue
                    return None
                    
            except requests.exceptions.Timeout:
                self.logger.warning(f"DeepSeek API调用超时 (第{attempt + 1}次)")
                if attempt < max_retries - 1:
                    self.logger.info(f"将在5秒后重试...")
                    import time
                    time.sleep(5)
                    continue
                return None
            except requests.exceptions.RequestException as e:
                self.logger.error(f"DeepSeek API网络错误: {str(e)}")
                if attempt < max_retries - 1:
                    self.logger.info(f"将在3秒后重试...")
                    import time
                    time.sleep(3)
                    continue
                return None
            except Exception as e:
                self.logger.error(f"DeepSeek API调用异常: {str(e)}")
                return None
        
        return None


# 创建全局实例（无API Key的本地分析版本）
deepseek_ai = DeepSeekAI()
